import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Drawer, Message, Icon, Box, Dialog, List } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { column } from './stores/definitions';
import { toJS } from 'mobx';
import { useHistory, useParams } from 'react-router';
import SettingSurcharge from './components/SettingSurcharge';

const tableId = uniqueId('tauTable-');

function CompanySettingRoute() {
  const { companyId } = useParams();
  const [modal, setModal] = useState([]);
  const [surcharge, setSurcharge] = useState([]);
  const [index, setIndex] = useState('');
  const { companySettingStore: store, companyStore } = useStore();
  const companyRef = useRef();
  const history = useHistory();
  const [currentPage, setCurrentPage] = useState(0); // 默认页数
  const [pageSize, setPageSize] = useState(10); // 每页显示的数据数量

  useEffect(() => {
    (async () => {
      await init();
      await store.getRules();
    })();
  }, []);

  // 根据当前页码和每页数量获取当前页需要显示的数据
  const startIndex = currentPage * pageSize;
  const endIndex = startIndex + pageSize;
  const currentPageData = surcharge.slice(startIndex, endIndex);

  /**
   * 初始化数据
   */
  const init = async () => {
    await store.get(companyId);
    await store.getSurcharge();
    setSurcharge([...toJS(store.charges)]);
  };

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { registerAddr, status, getOnDate, ...searchArgs } = params.values;
    const [from, to] = getOnDate || [];
    store.search = {
      registerAddr,
      status,
      from,
      to,
      ...searchArgs,
    };
  };

  // 点击打开添加
  const handleOpenAdd = () => {
    companyRef.current = {};
    setModal(['add']);
  };

  // 点击打开编辑
  const handleEdit = (result, i) => {
    companyRef.current = result;
    setIndex(i);
    setModal(['edit']);
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal([]);
  };

  /**
   * 添加费用
   * @param {*} result
   */
  const handleSettingPrice = async (result, state) => {
    if (!_.isEmpty(result)) {
      try {
        const check = surcharge.find((item) => item.name === result.name);
        if (check !== undefined) {
          Dialog.confirm({
            content: t`当前承运附加费用已存在,请重新添加`,
          });
          return;
        }
        surcharge.push(toJS(result));
        const resultMap = surcharge.reduce((accumulator, item) => {
          if (item.name === '夜间行驶费' || item.name === '假日附加费') {
            const findPrice = surcharge.find((n) => n.name === item.name);
            let prices = [];
            const price = state.map((p) => {
              return ({
                time: p.time,
                name: p.name,
                prices: { RMB: Number(p.price), HKD: Number(p.price), MOP: Number(p.price) },
              });
            });
            if (item.name === result.name) {
              prices = price;
            } else if (findPrice) {
              prices = findPrice.surcharge;
            }
            // eslint-disable-next-line no-param-reassign
            accumulator[item.name] = {
              ...item,
              surcharge: prices,
            };
          } else {
            // eslint-disable-next-line no-param-reassign
            accumulator[item.name] = { ...item, RMB: Number(item.RMB), HKD: Number(item.RMB), MOP: Number(item.RMB) };
          }
          return accumulator;
        }, {});

        const args = {
          ...toJS(store.company),
          surchargeSettlement: resultMap,
        };
        await store.update(args);
        Message.success({ content: t`价格添加成功` });
      } catch (error) {
        Message.error({ content: t`价格添加失败` });
        throw error;
      }
    }
    setModal([]);
    await init();
  };

  /**
   * 修改费用
   * @param {*} result
   */
  const handleEditPrice = async (result, state) => {
    if (!_.isEmpty(result)) {
      try {
        const check = surcharge.find((item) => item.name === result.name);
        if (check !== undefined && (surcharge[index].name !== check?.name)) {
          Dialog.confirm({
            content: t`当前承运附加费用已存在,请重新添加`,
          });
          return;
        }
        surcharge[index] = (toJS(result));
        const resultMap = surcharge.reduce((accumulator, item) => {
          if (item.name === '夜间行驶费' || item.name === '假日附加费') {
            const findPrice = surcharge.find((n) => n.name === item.name);
            let prices = [];
            const price = state.map((p) => {
              return ({
                time: p.time,
                name: p.name,
                prices: { RMB: Number(p.price), HKD: Number(p.price), MOP: Number(p.price) },
              });
            });
            if (item.name === result.name) {
              prices = price;
            } else if (findPrice) {
              prices = findPrice.surcharge;
            }
            // eslint-disable-next-line no-param-reassign
            accumulator[item.name] = {
              ...item,
              surcharge: prices,
            };
          } else {
            // eslint-disable-next-line no-param-reassign
            accumulator[item.name] = { ...item, RMB: Number(item.RMB), HKD: Number(item.RMB), MOP: Number(item.RMB) };
          }
          return accumulator;
        }, {});

        const args = {
          ...toJS(store.company),
          surchargeSettlement: resultMap,
        };
        await store.update(args);
        Message.success({ content: t`附加费用修政成功` });
      } catch (error) {
        Message.error({ content: t`附加费用修政失败` });
        throw error;
      }
    }
    setModal([]);
    await init();
  };

  /**
   * 删除附加费
   * @param {*} result
   * @param {*} i
   */
  const handleDelete = (result, i) => {
    if (!_.isEmpty(result)) {
      Dialog.confirm({
        content: t`确定要删除这条承运附加费用吗?`,
        onOk: async () => deleteSurcharge(i),
      });
    }
  };

  /**
   * 删除附加费事件回调
   * @param {*} i
   */
  const deleteSurcharge = async (i) => {
    try {
      surcharge.splice(i, 1);
      const resultMap = surcharge.reduce((accumulator, item) => {
        // eslint-disable-next-line no-param-reassign
        accumulator[item.name] = { ...item, RMB: Number(item.RMB), HKD: Number(item.RMB), MOP: Number(item.RMB) };
        return accumulator;
      }, {});
      const args = {
        ...toJS(store.company),
        surchargeSettlement: resultMap,
      };
      await store.update(args);
      Message.success({ content: t`附加费用删除成功` });
    } catch (error) {
      Message.error({ content: t`附加费用删除失败` });
      throw error;
    }
    await init();
  };

  return (
    <TauPage className="page-container">
      <Box direction="row" align="center" margin={10}>
        <Button type="normal" onClick={() => { history.goBack(); }} style={{ marginLeft: '-10px', border: 0 }}>
          <Icon type="arrow-left" style={{ padding: 6, border: '1px solid #ccc', borderRadius: '50%', color: 'var(--btn-pure-primary-bg)' }} />
        </Button>
        <div>{t`承运商【${companyStore.companyName}】的结算附加费用信息`}</div>
      </Box>
      <TauActionPanel
        onSearch={handleOnSearch}
        actions={[
          {
            name: 'btn-placeChannel',
            title: t`添加承运附加费`,
            type: 'primary',
            onClick: handleOpenAdd,
          },
        ]}
        keywordSearch={{
          enabled: false,
          placeholder: t`请输入关键字搜搜`,
        }}
        className="action-panel"
      />
      <div className="content">
        <TauTable
          instanceId={tableId}
          primaryKey="name"
          tableLayout="fixed"
          currentPage={currentPage}
          pageSize={pageSize}
          total={surcharge?.length}
          onFetch={({ page, size }) => {
            setCurrentPage(page);
            size && setPageSize(size);
          }}
          dataSource={currentPageData}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('name', { width: 88 }),
            column('type', { width: 88 }),
            column('RMB', {
              width: 100,
              cell: (v, _, company) => {
                if (company?.surcharge) {
                  return (<List
                    size="small"
                    dataSource={company.surcharge}
                    renderItem={(item) => (
                      <List.Item
                        key={item.id}
                        extra={t`费用: ${item.prices.RMB}`}
                      >
                        {t`时间段: ${item.time}`}
                      </List.Item>
                    )}
                  />);
                } else {
                  return <span>{v}</span>;
                }
              },
            }),
            {
              title: t`操作`,
              dataIndex: 'channelNumber',
              width: 200,
              cell: (_, i, company) => {
                return (
                  <>
                    <Button text type="primary" onClick={() => handleEdit(company, i)} >{t`编辑`}</Button>
                    <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                    <Button text type="primary" style={{ color: 'red' }} onClick={() => handleDelete(company, i)} >{t`删除`}</Button>
                  </>
                );
              },
            },
          ]}
        />
      </div>
      <Drawer
        visible={!!modal[0]}
        title={modal[0] === 'add' ? t`添加承运附加费` : t`修改承运附加费`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="600px"
      >
        <SettingSurcharge
          company={companyRef.current}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal[0] === 'add' ? handleSettingPrice : handleEditPrice}
        />
      </Drawer>
    </TauPage>
  );
}

export default observer(CompanySettingRoute);
